import json
import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from geetest.geetest_v3 import GeeTest3
from main_v2 import scroll_down

# Chrome浏览器
driver = webdriver.Chrome()


def print_hi(name):
  # Use a breakpoint in the code line below to debug your script.
  print(f'Hi, {name}')  #
  # 最大化
  driver.maximize_window()

  # driver.get(
  #     "https://www.shein.com.mx/1pc-Rhinestone-Butterfly-Tassel-Hair-Hoop-p-20093905.html?src_identifier=st%3D3%60sc%3DVinchas%60sr%3D0%60ps%3D6&src_module=search&src_tab_page_id=page_store1710428377649&mallCode=1&pageListType=4")
  data = requests.get('http://shein.jxwazx.cn/api/getRandSyncDetail')
  first = True
  while data.text != None:
    # 页面缩小
    # zoom_out = "document.body.style.zoom='0.1'"
    # driver.execute_script(zoom_out)
    try:
      updateData(data.text, first)
    except Exception as e:
      print(e)
      pass
    first = False
    data = requests.get('http://shein.jxwazx.cn/api/getRandSyncDetail')


def check(driver):
  # 校验是否有验证码
  WebDriverWait(driver, 2).until(
      EC.visibility_of_element_located(
          (By.CSS_SELECTOR, '.geetest_canvas_bg'))
  )
  print("[step] 已找到验证码")

  geetest = GeeTest3()
  print("[step] 自动验证中")
  flag = geetest.run(driver)

  if flag:
    # 验证通过
    print('[step] 验证通过')
  else:
    print('[step] 验证失败，正在刷新网页重试')
    updateData(driver.current_url, True)


def updateData(data, first):
  # 发送请求
  headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
  }
  print('[start] 当前爬取的网页地址是：' + data)
  # 产品
  product = dict()

  driver.get(data)
  # if first == True:
  #   time.sleep(30)
  # else:
  #   time.sleep(3)

  try:
    print("[step] 检测验证码")
    check(driver)
  except:
    print("[step] 未检测到验证码")
    pass

  # 五级分类+
  typeList = driver.find_elements(By.CSS_SELECTOR, 'a.bread-crumb__item-link')
  # 下滑
  print("[step] 开始下滑")
  for i in range(1):
    scroll_down(driver)
  time.sleep(3)
  print("[step] 结束下滑")
  driver.execute_script(
      'document.querySelectorAll(\'i.iconfont.icon-close.she-close\')[0]?.click()')
  driver.execute_script(
      'document.querySelectorAll(\'.dialog-top__close-btn\')[0]?.click()')

  # 滑动到页面的特定位置，例如滑动到页面的底部
  # for i in range(len(typeList) - 1):
  #   product['type_' + str(i + 1)] = typeList[i + 1].text
  skuElements = driver.find_elements(By.CSS_SELECTOR,
                                     '.product-intro__head-sku')
  if len(skuElements) == 0:
    # 说明sku不存在 判断一下地商品是不是被删除了
    if "eliminado" in driver.find_element(By.CSS_SELECTOR,
                                          ".info__error-tips").text:
      # 确实删除了
      product['productUrl'] = data
      product['productDown'] = 1
      product['productDownMessage'] = driver.find_element(By.CSS_SELECTOR,
                                                          ".info__error-tips").text

      print(product)
      jsonStr = json.dumps(product)
      print(jsonStr)
      # 直接给post方法中的json参数赋值，赋json类型的数据
      response = requests.post(url="http://shein.jxwazx.cn/api/productDown",
                               headers=headers, json=product)
      page_text = response.text
      print(page_text)

  product['sku'] = driver.find_element(By.CSS_SELECTOR,
                                       '.product-intro__head-sku').text.removeprefix(
      'SKU: ')
  # 总评论数
  allCommentCountElements = driver.find_elements(By.CSS_SELECTOR,
                                                 '.product-intro__head-reviews-text')
  allCommentCount = 0
  if len(allCommentCountElements) > 0:
    allCommentCount = allCommentCountElements[0].text
  product['allCommentCount'] = allCommentCount

  # product['productPrice'] = driver.find_element(By.CSS_SELECTOR,
  #                                               '.from  span').text
  startTextElements = driver.find_elements(By.CSS_SELECTOR,
                                           '.product-intro__head-reviews-text')
  if len(startTextElements) > 0:
    product['startText'] = startTextElements[0].get_attribute('data-review-num')
  # 库存数量
  stockCount = None
  stockCountElements = driver.find_elements(By.CSS_SELECTOR,
                                            '.product-intro__qty-orange')
  # 是否参与闪购
  flashElements = driver.find_elements(
      By.CSS_SELECTOR, '.product-intro__PriceBannerType-headLeft'
  )
  if len(flashElements) > 0:
    product['joinQuick'] = flashElements[0].text
  if len(stockCountElements) > 0:
    stockCount = stockCountElements[0].text
  product['stockCount'] = stockCount
  sWitch = driver.find_elements(By.CSS_SELECTOR, '.c-switch')
  # 库存（缺货）情况
  product['lessFlag'] = driver.find_element(By.CSS_SELECTOR,
                                            '.product-intro__add-btn').text

  if len(sWitch) > 0:
    # 总评论数量
    product['allCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                     'h2.j-expose__common-review-container').get_attribute(
        'aria-label')
    # 总评论分数
    product['allCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                     '.rate-num').text
    # 切换成本土
    driver.execute_script("document.querySelectorAll('.c-switch')[0].click()")
    time.sleep(5)
    # 本土评论数量
    product['locationCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                          'h2.j-expose__common-review-container').get_attribute(
        'aria-label')
    # 本土评论分数
    product['locationCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                          '.rate-num').text
    # 切换最新评论
    driver.execute_script(
        "document.querySelectorAll('.common-reviews__select-box-list > li[data-sort-type]')[0].click()");
    # 等待5秒
    time.sleep(5)
    # 抓取第一个
    product['locationCommentLastTimeStr'] = driver.find_element(By.CSS_SELECTOR,
                                                                '.common-reviews-new__top-baseinfo .date').text
  else:
    # 不应该出现 但是给他pass
    # print('[error] 抓取不到产品评论信息')
    # check(driver)
    # 总评论数量
    product['allCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                     'h2.j-expose__common-review-container').get_attribute(
        'aria-label')
    # 总评论分数
    product['allCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                     '.rate-num').text
    # 本土评论数量
    product['locationCommentCount'] = driver.find_element(By.CSS_SELECTOR,
                                                          'h2.j-expose__common-review-container').get_attribute(
        'aria-label')
    # 本土评论分数
    product['locationCommentScore'] = driver.find_element(By.CSS_SELECTOR,
                                                          '.rate-num').text
    # 抓取第一个
    dateElements = driver.find_elements(By.CSS_SELECTOR,
                                        '.common-reviews-new__top-baseinfo .date')
    if len(dateElements) != 0:
      product['locationCommentLastTimeStr'] = driver.find_element(
          By.CSS_SELECTOR,
          '.common-reviews-new__top-baseinfo .date').text

  shopNameElements = driver.find_elements(By.CSS_SELECTOR,
                                          '.shop-entry__storeEntry .title')
  if len(shopNameElements) == 0:
    product['shopName'] = "无店铺产品"
  else:
    # 抓取店铺名称
    product['shopName'] = driver.find_element(By.CSS_SELECTOR,
                                              '.shop-entry__storeEntry .title').text
    if product['shopName'] == '':
      print('[info] 页面获取不到店铺名称')
      print('[step] 自动展开店铺信息中')
      driver.execute_script(
          "document.querySelectorAll('.product-intro__brand-head')[0]?.click()");
      product['shopName'] = driver.find_element(By.CSS_SELECTOR,
                                                '.shop-entry__storeEntry .title').text
      time.sleep(1)
    if product['shopName'] == '':
      print('[error] 展开后获取不到店铺名称 地址：' + data)
      driver.execute_script(
          "document.querySelectorAll('.product-intro__brand-head')[0]?.click()");
      product['shopName'] = driver.find_element(By.CSS_SELECTOR,
                                                '.shop-entry__storeEntry .title').text
      time.sleep(1)
    if product['shopName'] == '':
      print('[error] 展开后获取不到店铺名称 地址：' + data)
      driver.execute_script(
          "document.querySelectorAll('.product-intro__brand-head')[0]?.click()");
      product['shopName'] = driver.find_element(By.CSS_SELECTOR,
                                                '.shop-entry__storeEntry .title').text

      print('[step] 设置为无店铺产品')
      # return
  infoElement = driver.find_elements(By.CSS_SELECTOR, '.follow-info-line em')
  if len(infoElement) > 2:
    # 店铺分数
    product['shopScore'] = infoElement[0].text
    # 店铺的产品数量
    product['shopProductCount'] = infoElement[1].text
  else:
    # 店铺的产品数量
    product['shopProductCount'] = infoElement[0].text

  # 店铺id获取
  dataId = driver.find_element(By.CSS_SELECTOR,
                               '.shop-entry_JumpToStoreBtn').get_attribute(
      'data-id')
  product[
    'shopUrl'] = "https://www.shein.com.mx/store/home?store_code=" + dataId + "&type=selection&tab=items"
  driver.execute_script(
      'document.querySelectorAll(".product-intro__description-head")[0].click()')
  # 取出文字
  time.sleep(3)
  product['describe'] = driver.find_element(By.CSS_SELECTOR,
                                            '.product-intro__description-table').text
  print(product)
  productList = [product]
  # 发送请求
  url = 'http://shein.jxwazx.cn/api/batchSaveOrUpdate'
  print(productList)
  jsonStr = json.dumps(productList)
  print(jsonStr)
  # 直接给post方法中的json参数赋值，赋json类型的数据
  response = requests.post(url=url, headers=headers, json=productList)
  page_text = response.text
  print(page_text)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
  print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
